package cn.zhiquxing.excel;

import cn.zhiquxing.vo.ImportData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

@Repository
@Slf4j
public class DataRepository {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    
    @Autowired
    private EntityManager entityManager;
    
    // 使用JdbcTemplate批量插入，性能更高
    public void batchSave(List<ImportData> dataList) {
        String sql = "INSERT INTO import_data (name, phone, address, external_id, processed) VALUES (?, ?, ?, ?, ?)";
        
        jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement ps, int i) throws SQLException {
                ImportData data = dataList.get(i);
                ps.setString(1, data.getName());
                ps.setString(2, data.getPhone());
                ps.setString(3, data.getAddress());
                ps.setString(4, data.getExternalId());
                ps.setBoolean(5, data.getProcessed());
            }
            
            @Override
            public int getBatchSize() {
                return dataList.size();
            }
        });
    }
    
    // 保存失败记录
    public void saveErrorRecord(ImportData data) {
        String sql = "INSERT INTO import_error_data (name, phone, address, error_msg) VALUES (?, ?, ?, ?)";
        jdbcTemplate.update(sql, data.getName(), data.getPhone(), data.getAddress(), data.getErrorMsg());
    }
}